package com.lonely.order.support.synchronizer.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.lonely.order.domain.dto.api.QueryProduceOrderIdsReqDTO;
import com.lonely.order.domain.entity.SysSheinOpenApiSecret;
import com.lonely.order.service.IMesApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: 黄志标
 * @date: 2025/6/23 13:09
 * @description: 开始订单同步服务
 */
@Slf4j
@Service
public class StartSynchronizerOrderService {

    private static final IMesApiService MES_API_SERVICE = SpringUtil.getBean(IMesApiService.class);

    private static final RedissonClient REDISSON_CLIENT = SpringUtil.getBean(RedissonClient.class);

    private static final SynchronizerOrderService SYNCHRONIZER_ORDER_SERVICE = SpringUtil.getBean(SynchronizerOrderService.class);
    private static final SynchronizerOrderPurchaseService SYNCHRONIZER_ORDER_PURCHASE_SERVICE = SpringUtil.getBean(SynchronizerOrderPurchaseService.class);

    /**
     * 同步指定日期的订单数据
     *
     * @param date
     */
    public void synchronizerOrderByDate(SysSheinOpenApiSecret openApiSecret, Date date) {

        // 构建rediskey
        String currentDateStr = DateUtil.format(date, "yyyyMMdd");
        String lockKey = String.format("synchronizer:orders:%s:%s", openApiSecret.getFactoryId(), currentDateStr);
        RLock lock = REDISSON_CLIENT.getLock(lockKey);
        boolean isLocked = false;
        try {
            // 尝试获取锁，参数分别是等待时间、锁自动释放时间、时间单位
            // 不等待，直接尝试获取锁，获取成功则执行逻辑
            isLocked = lock.tryLock(0, 10, TimeUnit.SECONDS);
            if (!isLocked) {
                // 执行需要加锁保护的操作
                log.debug("同步工厂id：{}，日期：{} 的订单未获取到锁,退出此次同步", openApiSecret.getFactoryId(), currentDateStr);
                return;
            }

            // 获取指定日期的订单号
            List<Long> orderIdsByDate = getOrderIdsByDate(openApiSecret, date);

            // 同步订单
            SYNCHRONIZER_ORDER_SERVICE.synchronizerOrder(openApiSecret, orderIdsByDate);

            // 同步订单采购数据
            SYNCHRONIZER_ORDER_PURCHASE_SERVICE.synchronizerOrderPurchase(openApiSecret, orderIdsByDate);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("同步工厂id：{}，日期：{} 的订单出现异常，异常原因：{}", openApiSecret.getFactoryId(), currentDateStr, ExceptionUtils.getStackTrace(e));
        } finally {
            // 确保在finally块中释放锁
            if (isLocked && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


    /**
     * 获取指定日期的订单集合
     *
     * @param date
     * @return
     */
    private static List<Long> getOrderIdsByDate(SysSheinOpenApiSecret sheinOpenApiSecret, Date date) {
        // 1. 获取指定日期订单id集合
        QueryProduceOrderIdsReqDTO queryProduceOrderIdsReqDTO = new QueryProduceOrderIdsReqDTO();
        queryProduceOrderIdsReqDTO.setStartTime(DateUtil.beginOfDay(date).toStringDefaultTimeZone());
        queryProduceOrderIdsReqDTO.setEndTime(DateUtil.endOfDay(date).toStringDefaultTimeZone());
        return MES_API_SERVICE.queryProduceOrderIds(sheinOpenApiSecret, queryProduceOrderIdsReqDTO).stream().map(Convert::toLong).collect(Collectors.toList());
    }


}
